package com.swim.session;

import java.util.List;

import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.LocalBinding;
import org.jboss.ejb3.annotation.RemoteBinding;

import com.swim.entity.Collaboration;
import com.swim.entity.Feedback;

@Stateless
@RemoteBinding(jndiBinding="FeedbackBeanJNDI")
public class FeedbackBean implements FeedbackRemote {
	
	@PersistenceContext(unitName = "SWIM")
	EntityManager database;
	

	/**
	 * @param collabID the id of a collaboration
	 * @param rating the assessement to be included in the feedback
	 * @param desc the description to be included in the feedback
	 * @return the user that is using the application
	 */
	public void addFeedback(int collabID, int rating, String desc) {
		Feedback f = new Feedback(desc, rating);
		CollaborationLocal cLocal = getCollaborationLocal();
		Collaboration c = cLocal.getCollaboration(collabID);
		c.setIdFeedback(f);
		database.persist(f);
	}
	

	/**
	 * @param id the id of the feedback
	 * @return the feedback selected by the id
	 */
	public Feedback getFeedbackById(int id) {
		try{
			Query q = database.createQuery("SELECT f FROM Feedback f WHERE f.id=:id");
			q.setParameter("id", id);
			Feedback result =  (Feedback) q.getSingleResult();
			return result;
	   	} catch (EntityNotFoundException exc) { 
			System.err.println("UFF1");
		} catch (javax.persistence.NoResultException exc) { 
			System.err.println("UFF2");
		} catch (NonUniqueResultException exc) {
			System.err.println("UFF3");
		}
		return null;
	}
	
	/**
	 * @return the local interface of collaboration
	 */
	private CollaborationLocal getCollaborationLocal() {
		InitialContext jndiContext;
		Object ref = null;
		try {
			jndiContext = new InitialContext();
			ref = jndiContext.lookup("CollaborationBeanLocalJNDI");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (CollaborationLocal) ref;
	}

	/**
	 * @param email the email of the user who received a feedback
	 * @return the list of the feedback received from the user
	 */
	public List<Feedback> getFeedbackByUser(String email) {
		try{
			Query q = database.createQuery("SELECT f FROM Feedback f,Collaboration c WHERE f.id=c.idFeedback AND c.emailFrom.email=:emailFrom");
			q.setParameter("emailFrom", email);
			List<Feedback> result =  (List<Feedback>) q.getResultList();
			return result;
	   	} catch (EntityNotFoundException exc) { 
			System.err.println("UFF1");
		} catch (javax.persistence.NoResultException exc) { 
			System.err.println("UFF2");
		} catch (NonUniqueResultException exc) {
			System.err.println("UFF3");
		}
		return null;
	}
}
